﻿using SqlSugar;

namespace Api
{
    public static class SqlSugarConfiguration
    {
        public static void AddSqlSugarConfiguration(this IServiceCollection services)
        {
            var conn1 = new ConnectionConfig
            {
                DbType = DbType.SqlServer,
                ConnectionString = AppSetting.ConnectionStrings.MS_SQL,
                IsAutoCloseConnection = true,
            };

            //var conn2 = new ConnectionConfig
            //{
            //    ConfigId = "db2",
            //    DbType = DbType.SqlServer,
            //    ConnectionString = AppSetting.ConnectionStrings.MS_SQL,
            //    IsAutoCloseConnection = true,
            //};

            SqlSugarScope sqlSugarScope = new(
                new List<ConnectionConfig> { conn1 },
                //new List<ConnectionConfig> { conn1, conn2 },
                db =>
                {
                    //sql执行前
                    db.Aop.OnLogExecuting = (sql, pars) =>
                    {
                        //记录执行的sql
                        if (AppSetting.Config.SystemSwitch.IsSqlLog)
                        {
                            Gx.Log(UtilMethods.GetSqlString(DbType.MySql, sql, pars, true), "SQL日志-");
                        }
                    };

                    //sql报错
                    db.Aop.OnError = (ex) =>
                    {
                        //记录sql报错的sql
                        if (AppSetting.Config.SystemSwitch.IsSqlLog)
                        {
                            Gx.Log(UtilMethods.GetSqlString(DbType.MySql, ex.Sql, (SugarParameter[])ex.Parametres, true), "SQL异常-");
                        }
                    };
                }
            );

            services.AddSingleton<ISqlSugarClient>(sqlSugarScope);
        }
    }
}
